using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Rilisoft.MiniJson;
using UnityEngine;

public class VersionSelector : MonoBehaviour
{
	private const string bcwConfig = "bcw-config/";

	public static string authAddress_ = "213.133.110.204:8090";

	private static bool lastValue;

	private static bool isPathed;

	private static string lastHash = string.Empty;

	private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
	{
		Debug.LogFormat("Resolving assembly (name={0})", args.Name);
		try
		{
			return AppDomain.CurrentDomain.Load(args.Name);
		}
		catch (Exception exception)
		{
			Debug.LogException(exception);
			Debug.LogErrorFormat("Failed to load Neutrino assembly");
			return null;
		}
	}

	private string CheckAddressOverride(string value)
	{
		if (authAddress_.Length == 0)
		{
			return value;
		}
		int[] array = new int[4] { 5058, 4533, 9093, 19093 };
		foreach (int num in array)
		{
			string text = "ns.exitgames.com:" + num;
			int num2 = value.IndexOf(text);
			if (num2 >= 0)
			{
				return value.Replace(text, authAddress_);
			}
		}
		return value;
	}

	private void Awake()
	{
		Assembly assembly = null;
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly2 in assemblies)
		{
			if (assembly2.GetName().Name == "Neutrino3Unity3D")
			{
				assembly = assembly2;
				break;
			}
		}
		if (assembly == null)
		{
			Debug.Log("Neutrino assembly not found, waiting for resolve");
			AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
		}
		else
		{
			Debug.Log("Neutrino assembly found, patching");
			isPathed = true;
			SetConnectCallback(assembly);
		}
	}

	private void SetConnectCallback(Assembly assembly)
	{
		Type[] types = assembly.GetTypes();
		foreach (Type type in types)
		{
			if (!(type.Name != "SupportClass"))
			{
				MethodInfo method = type.GetMethod("SetAddressOverrideFunc", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (method != null)
				{
					Func<string, string> func = CheckAddressOverride;
					method.Invoke(null, new object[1] { func });
				}
				Debug.Log("Neutrino assembly patched successfully");
				break;
			}
		}
	}

	public static IEnumerator DownloadNeutrinoSignaturesCoroutine(MonoBehaviour mb)
	{
		bool needDownloadJson = false;
		string fileName = GetServerPath(URLs.Neutrino);
		string namesSerialized = "[\"" + fileName + "\"]";
		WWWForm form = new WWWForm();
		form.AddField("app_version", BCWServer._version);
		form.AddField("prefix", "bcw-config");
		form.AddField("names", namesSerialized);
		WWW www = new WWW("https://secure.pixelgunserver.com/get_files_info.php", form);
		if (www == null)
		{
			BCWDebug.LogError("Error download file info");
			yield break;
		}
		while (!www.isDone)
		{
			yield return null;
		}
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.LogError("Error download file info " + www.error);
			needDownloadJson = true;
		}
		BCWDebug.LogError("Signature Response: " + www.text);
		Dictionary<string, object> urlsHash = Json.Deserialize(www.text) as Dictionary<string, object>;
		if (urlsHash != null && urlsHash.ContainsKey(fileName))
		{
			if (!(urlsHash[fileName] as string).Equals(lastHash))
			{
				lastHash = urlsHash[fileName] as string;
				needDownloadJson = true;
				BCWDebug.LogError("New hash - start download json : " + urlsHash[fileName]);
			}
		}
		else
		{
			needDownloadJson = true;
			BCWDebug.LogError("Response not Contains Key- start download json");
		}
		if (needDownloadJson)
		{
			yield return mb.StartCoroutine(LoadNeutrinoJson());
		}
	}

	private static IEnumerator LoadNeutrinoJson()
	{
		bool usePhoton = false;
		WWW www = new WWW(URLs.Neutrino);
		while (!www.isDone)
		{
			yield return null;
		}
		string result = BCWServer.Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("NeutrinoConfig Error download:  " + www.error);
			usePhoton = true;
		}
		else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("NeutrinoConfig failed ");
			usePhoton = true;
		}
		else if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("NeutrinoConfig result is empty");
			usePhoton = true;
		}
		else
		{
			BCWDebug.Log("NeutrinoConfig result " + result);
			Dictionary<string, object> responseDictionary = Json.Deserialize(result) as Dictionary<string, object>;
			if (responseDictionary != null && responseDictionary.ContainsKey("EnableNeutrino") && (long)responseDictionary["EnableNeutrino"] != 1)
			{
				usePhoton = true;
			}
		}
		if (usePhoton)
		{
			authAddress_ = string.Empty;
		}
		else
		{
			authAddress_ = "blockcity-srv1.myghtyblock.com:8090";
		}
		if (lastValue != usePhoton)
		{
			if (isPathed)
			{
				PhotonNetwork.Disconnect();
				BCWDebug.Log("Server changed - Disconnect from current");
			}
			lastValue = usePhoton;
		}
		yield return null;
	}

	private static string GetServerPath(string s)
	{
		return s.Substring(URLs.CheckVersion.IndexOf("bcw-config/") + "bcw-config/".Length);
	}
}
